import json
from datetime import datetime

from django.http import JsonResponse
from django.views import View

from lapi_app.models.testcase_model.testcase import Testcase, Asserts
from lapi_app.models.testcase_model.testcase_tree import Menu


class Copy_case(View):

    def post(self, request, *args, **kwargs):
        body = json.loads(request.body)
        label = body["label"]
        pid = body["pid"]
        t = body["type"]
        cid = body["id"]
        user_id = body["user_id"]

        if label == '' or pid == '' or t == '' or user_id == '' or cid == '':
            return JsonResponse({
                "code": 100,
                "message": "必要参数不能为空"
            })
        else:
            case_ids = Menu.objects.filter(id=cid)
            for case_id in case_ids:
                case_id = case_id.testcase_id
                cases = Testcase.objects.filter(id=case_id)
                for case in cases:
                    c = Testcase(t_name=case.t_name + 'copy', t_method=case.t_method,
                                 t_url=case.t_url, t_params=case.t_params, t_type=case.t_type,
                                 t_header=case.t_header, t_body=case.t_body, t_extract=case.t_extract,
                                 update_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                 create_time=datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
                                 t_environment_id=case.t_environment_id, t_user_id=user_id)
                    c.save()
                    m = Menu(label=label + 'copy', pid=pid, type=t, m_user_id=user_id, testcase_id=c.id)
                    m.save()
                    asserts = Asserts.objects.filter(assert_testcase_id=case_id)
                    for a in asserts:
                        assert_data = Asserts(assert_key=a.assert_key,
                                              assert_value=a.assert_value,
                                              assert_testcase_id=c.id)
                        assert_data.save()
                return JsonResponse({
                    "code": 200,
                    "message": "复制接口成功",
                    "data": {"id": m.id, "type": t, "label": m.label, "pid": pid}
                })
